﻿using System;
using System.ComponentModel;
using System.Xml.Serialization;
using Microsoft.WowAddonStudio.FrameXml.Serialization.Enumerations;
using Microsoft.WowAddonStudio.FrameXml.Serialization.Support;

namespace Microsoft.WowAddonStudio.FrameXml.Serialization.LayoutFrames
{
    public abstract class LayeredLayoutFrame : LayoutFrame
    {
        private DrawLayer drawLayer;

        /// <summary>
        /// Initializes a new instance of the <see cref="LayeredLayoutFrame"/> class.
        /// </summary>
        protected LayeredLayoutFrame(DrawLayer drawLayer)
        {
            this.drawLayer = drawLayer;
        }

        /// <summary>
        /// Gets or sets the <see cref="DrawLayer"/> the layout frame is drawn on.
        /// </summary>
        [XmlIgnore]
        public DrawLayer DrawLayer
        {
            get
            {
                // Gets the parent of control.
                if (this.ParentFrame != null)
                {
                    // Check whether the parent contais layer.
                    LayerList layerList = this.ParentFrame.GetInheritableList<Layer, LayerList>("Layers");

                    if (layerList != null && layerList.Count > 0 && !String.IsNullOrEmpty(this.Name))
                    {
                        // Gets layer for actual control.
                        Layer layer = layerList.GetLayer(this.Name);

                        if (layer != null)
                            drawLayer = layer.Level;
                    }
                }

                return drawLayer;
            }
            set
            {
                if (drawLayer != value)
                {
                    // Draw layer changed, remove LayeredLayoutFrame with current layer
                    if (this.ParentFrame is ISerializationObjectContainer)
                        ((ISerializationObjectContainer)this.ParentFrame).Remove(this);

                    // Update the draw layer
                    drawLayer = value;

                    // Add LayeredLayoutFrame with new layer
                    if (this.ParentFrame is ISerializationObjectContainer)
                        ((ISerializationObjectContainer)this.ParentFrame).Add(this);
                }

                OnPropertyChanged(new PropertyChangedEventArgs("DrawLayer"));
            }
        }
    }
}